<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="锁,并发,Java基础,">










<meta name="description" content="锁 JAVA中的锁锁的分类 公平锁 / 非公平锁可重入锁独享锁 / 共享锁互斥锁 / 读写锁乐观锁 / 悲观锁分段锁偏向锁 / 轻量级锁 / 重量级锁自旋锁  公平锁 / 非公平锁公平锁：按照申请顺序来获取锁非公平锁：会造成优先级反转或者饥饿现象对于ReentrantLock而言，可以通过指定构造函数中fair设置是否公平锁非公平锁的吞吐量比公平锁更大(Synchronized) 可重入锁又叫递归">
<meta name="keywords" content="锁,并发,Java基础">
<meta property="og:type" content="article">
<meta property="og:title" content="Java中的锁">
<meta property="og:url" content="http://koude.gitee.io/blog/2019/03/02/va中的锁/index.html">
<meta property="og:site_name" content="JavaKK">
<meta property="og:description" content="锁 JAVA中的锁锁的分类 公平锁 / 非公平锁可重入锁独享锁 / 共享锁互斥锁 / 读写锁乐观锁 / 悲观锁分段锁偏向锁 / 轻量级锁 / 重量级锁自旋锁  公平锁 / 非公平锁公平锁：按照申请顺序来获取锁非公平锁：会造成优先级反转或者饥饿现象对于ReentrantLock而言，可以通过指定构造函数中fair设置是否公平锁非公平锁的吞吐量比公平锁更大(Synchronized) 可重入锁又叫递归">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-03-28T09:09:44.460Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java中的锁">
<meta name="twitter:description" content="锁 JAVA中的锁锁的分类 公平锁 / 非公平锁可重入锁独享锁 / 共享锁互斥锁 / 读写锁乐观锁 / 悲观锁分段锁偏向锁 / 轻量级锁 / 重量级锁自旋锁  公平锁 / 非公平锁公平锁：按照申请顺序来获取锁非公平锁：会造成优先级反转或者饥饿现象对于ReentrantLock而言，可以通过指定构造函数中fair设置是否公平锁非公平锁的吞吐量比公平锁更大(Synchronized) 可重入锁又叫递归">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://koude.gitee.io/blog/2019/03/02/va中的锁/">





  <title>Java中的锁 | JavaKK</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">JavaKK</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Welcome To My Blog</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://koude.gitee.io/blog/blog/2019/03/02/va中的锁/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="JavaKK">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JavaKK">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java中的锁</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-02T22:36:00+08:00">
                2019-03-02
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java基础/" itemprop="url" rel="index">
                    <span itemprop="name">Java基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="锁"><a href="#锁" class="headerlink" title="锁"></a>锁</h1><hr>
<h2 id="JAVA中的锁"><a href="#JAVA中的锁" class="headerlink" title="JAVA中的锁"></a>JAVA中的锁</h2><h2 id="锁的分类"><a href="#锁的分类" class="headerlink" title="锁的分类"></a>锁的分类</h2><blockquote>
<p>公平锁 / 非公平锁<br>可重入锁<br>独享锁 / 共享锁<br>互斥锁 / 读写锁<br>乐观锁 / 悲观锁<br>分段锁<br>偏向锁 / 轻量级锁 / 重量级锁<br>自旋锁</p>
</blockquote>
<h3 id="公平锁-非公平锁"><a href="#公平锁-非公平锁" class="headerlink" title="公平锁 / 非公平锁"></a>公平锁 / 非公平锁</h3><p>公平锁：按照申请顺序来获取锁<br>非公平锁：会造成优先级反转或者饥饿现象<br>对于ReentrantLock而言，可以通过指定构造函数中fair设置是否公平锁<br>非公平锁的吞吐量比公平锁更大(Synchronized)</p>
<h3 id="可重入锁"><a href="#可重入锁" class="headerlink" title="可重入锁"></a>可重入锁</h3><p>又叫递归锁，可一定程度上避免死锁<br>ReentrantLock和Synchronized都是可重入锁<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">setA</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">    Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">    setB();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">setB</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">    Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="独享锁-共享锁"><a href="#独享锁-共享锁" class="headerlink" title="独享锁 / 共享锁"></a>独享锁 / 共享锁</h3><p>独享锁是指该锁一次只能被一个线程所持有。<br>共享锁是指该锁可被多个线程所持有。<br>ReadWriteLock：读是共享锁，写是独享锁</p>
<h3 id="互斥锁-读写锁"><a href="#互斥锁-读写锁" class="headerlink" title="互斥锁 / 读写锁"></a>互斥锁 / 读写锁</h3><p>是独享锁和共享锁的一种具体实现<br>互斥锁的具体实现 -&gt; ReentrantLock<br>读写锁的具体实现 -&gt; ReadWriteLock</p>
<h3 id="乐观锁-悲观锁"><a href="#乐观锁-悲观锁" class="headerlink" title="乐观锁 / 悲观锁"></a>乐观锁 / 悲观锁</h3><p>看待并发同步的角度<br>乐观锁，多读少写的场景，CAS实现<br>悲观锁，多写少读的场景，每次都加锁</p>
<h3 id="分段锁"><a href="#分段锁" class="headerlink" title="分段锁"></a>分段锁</h3><p>一种锁的设计，不是具体的锁<br>例如 ConcurrentHashMap中的分段锁称为Segment，更新操作时不是对整个hashmap加锁，在需要操作的分段中加锁，在获取全局信息的时候，需要获取全部Segment的锁才能统计</p>
<h3 id="偏向锁-轻量级锁-重量级锁"><a href="#偏向锁-轻量级锁-重量级锁" class="headerlink" title="偏向锁 / 轻量级锁 / 重量级锁"></a>偏向锁 / 轻量级锁 / 重量级锁</h3><p>指锁的状态，针对Synchronize。<br>偏向锁：一段同步代码一直被一个线程访问，那么该线程会自动获得锁，降低获取锁的代价<br>轻量级锁：当锁是偏向锁的时候，被另一个线程访问，偏向锁就会变成轻量级锁，线程通过自旋的锁，不会阻塞，提高性能<br>重量级锁：当锁为轻量级的时候，另一个线程是自旋的，但自旋不会一直下去，当自旋到一定次数后，若还没有获取到锁，就会进入阻塞</p>
<h3 id="自旋锁"><a href="#自旋锁" class="headerlink" title="自旋锁"></a>自旋锁</h3><p>线程获取锁，不会立即阻塞，而是采用循环的方式尝试获取锁，好处是减少上下文切换的消耗，缺点是消耗CPU资源</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/锁/" rel="tag"># 锁</a>
          
            <a href="/blog/tags/并发/" rel="tag"># 并发</a>
          
            <a href="/blog/tags/Java基础/" rel="tag"># Java基础</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/02/12/实习报告/" rel="next" title="实习报告">
                <i class="fa fa-chevron-left"></i> 实习报告
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/03/06/SpringCloud基础/" rel="prev" title="SpringCloud基础">
                SpringCloud基础 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">JavaKK</p>
              <p class="site-description motion-element" itemprop="description">Be Better No Ego</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">28</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/javakk" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:92920@sohu.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://www.javakk.cn" target="_blank" title="Resume">
                      
                        <i class="fa fa-fw fa-instagram"></i>Resume</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#锁"><span class="nav-number">1.</span> <span class="nav-text">锁</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#JAVA中的锁"><span class="nav-number">1.1.</span> <span class="nav-text">JAVA中的锁</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#锁的分类"><span class="nav-number">1.2.</span> <span class="nav-text">锁的分类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#公平锁-非公平锁"><span class="nav-number">1.2.1.</span> <span class="nav-text">公平锁 / 非公平锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#可重入锁"><span class="nav-number">1.2.2.</span> <span class="nav-text">可重入锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#独享锁-共享锁"><span class="nav-number">1.2.3.</span> <span class="nav-text">独享锁 / 共享锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#互斥锁-读写锁"><span class="nav-number">1.2.4.</span> <span class="nav-text">互斥锁 / 读写锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#乐观锁-悲观锁"><span class="nav-number">1.2.5.</span> <span class="nav-text">乐观锁 / 悲观锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#分段锁"><span class="nav-number">1.2.6.</span> <span class="nav-text">分段锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#偏向锁-轻量级锁-重量级锁"><span class="nav-number">1.2.7.</span> <span class="nav-text">偏向锁 / 轻量级锁 / 重量级锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自旋锁"><span class="nav-number">1.2.8.</span> <span class="nav-text">自旋锁</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Powered by JavaKK</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/blog/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/blog/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  

  

  

</body>
</html>
